<template>
  <view class="container">
    <!-- 结果显示 -->
    <scroll-view scroll-y class="result-box">
      <text>{{ resultText }}</text>
    </scroll-view>
    
    <!-- 控制按钮 -->
    <button 
      class="record-btn" 
      @touchstart="startRecord" 
      @touchend="stopRecord"
      :class="{ recording: isRecording }"
    >
      {{ isRecording ? '松开结束' : '长按说话' }}
    </button>
    
    <!-- 状态反馈 -->
    <view v-if="isRecording" class="status-indicator">
      <view class="pulse-ring"></view>
      <view class="pulse-dot"></view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'

const isRecording = ref(false)
const resultText = ref('')
let manager = null
let tempFilePath = ''
const plugin = requirePlugin('WechatSI')

onMounted(() => {
  // 初始化语音识别管理器
  manager = plugin.getRecordRecognitionManager()
  
  // 设置事件监听
  manager.onStart = () => console.log("录音开始")
  manager.onError = (err) => {
    console.error('语音识别错误:', err)
    uni.showToast({ title: '识别失败，请重试', icon: 'none' })
  }
  manager.onStop = (res) => tempFilePath = res.tempFilePath
  manager.onRecognize = (res) => resultText.value = res.result
  manager.onResult = (res) => {
    if (res.result) resultText.value = res.result
    uni.showToast({ title: '识别完成', icon: 'success' })
  }
})

const startRecord = async () => {
  // 检查插件是否初始化
  if (!plugin) {
    uni.showToast({ title: '插件初始化失败', icon: 'none' })
    return
  }
  
  try {
    // 获取录音权限
    const res = await uni.getSetting()
    if (!res.authSetting['scope.record']) {
      await uni.authorize({ scope: 'scope.record' })
    }
    
    // 开始录音
    manager.start({ duration: 60000 }) // 最长60秒
    isRecording.value = true
    resultText.value = '正在聆听...'
    
  } catch (err) {
    console.error('开始录音失败:', err)
    uni.showToast({ title: '录音权限未开启', icon: 'none' })
  }
}

const stopRecord = () => {
  if (!isRecording.value) return
  
  try {
    // 停止录音
    manager.stop()
    isRecording.value = false
    
  } catch (err) {
    console.error('停止录音失败:', err)
    isRecording.value = false
  }
}
</script>

<style scoped>
.container {
  padding: 20rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.result-box {
  width: 90%;
  height: 300rpx;
  border: 1px solid #eee;
  border-radius: 16rpx;
  padding: 20rpx;
  margin-bottom: 60rpx;
}

.record-btn {
  width: 250rpx;
  height: 250rpx;
  border-radius: 50%;
  font-size: 32rpx;
  background-color: #07c160;
  color: white;
}

.recording {
  background-color: #e64340 !important;
}

.status-indicator {
  position: relative;
  margin-top: 40rpx;
}

.pulse-ring {
  position: absolute;
  width: 100rpx;
  height: 100rpx;
  border: 4rpx solid #e64340;
  border-radius: 50%;
  animation: pulse 1.5s ease-out infinite;
}

.pulse-dot {
  width: 30rpx;
  height: 30rpx;
  background-color: #e64340;
  border-radius: 50%;
}

@keyframes pulse {
  0% { transform: scale(0.8); opacity: 1; }
  100% { transform: scale(2); opacity: 0; }
}
</style>